package com.lzh.hosp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.hosp.model.Doctor;
import com.lzh.hosp.model.vo.DoctorQueryVo;
import com.lzh.hosp.service.DictService;
import com.lzh.hosp.service.DoctorService;
import com.lzh.hosp.mapper.DoctorMapper;
import com.lzh.hosp.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
* @author 59399
* @description 针对表【doctor】的数据库操作Service实现
* @createDate 2023-03-16 09:33:52
*/
@Service
public class DoctorServiceImpl extends ServiceImpl<DoctorMapper, Doctor>
    implements DoctorService{

    @Autowired
    private DictService dictService;

    @Override
    public DoctorQueryVo getDocInfo(Long userId) {
        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();
        wrapper.eq("account_id",userId);
        Doctor doctor = baseMapper.selectOne(wrapper);
        DoctorQueryVo doctorQueryVo = new DoctorQueryVo();

        if (doctor!=null){
            BeanUtils.copyProperties(doctor,doctorQueryVo);
            //补充完整doctorQueryVo中的信息
            if (doctor.getGender()==0){
                doctorQueryVo.setGender("男");
            }else{
                doctorQueryVo.setGender("女");
            }

            //查询出科室名称
            doctorQueryVo.setDepName(dictService.getDictName(doctor.getDepcode()));
            return doctorQueryVo;
        }
        return doctorQueryVo;
    }

    @Override
    public boolean isAuth(HttpServletRequest request) {
        String jwt = request.getHeader("token");
        if (StringUtils.isEmpty(jwt)) {
            return false;
        }

        Claims claim = null;
        try {
            claim = JwtUtil.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (claim == null) {
            throw new JwtException("token 异常");
        }
        if (JwtUtil.isTokenExpired(claim)) {
            throw new JwtException("token已过期");
        }

        String userid = claim.getSubject();
        int userIdInt = Integer.parseInt(userid);
        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();
        wrapper.eq("account_id",userIdInt);
        Doctor doctor = baseMapper.selectOne(wrapper);
        if (StringUtils.isEmpty(doctor)){
            return false;
        }
        return doctor.getAuthStatus()==1?true:false;
    }
}




